package com.app.controller.supermarket;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.app.conf.RedisService;
import com.app.model.supermarket.MktPersonModel;
import com.app.service.supermarket.MktPersonService;
import com.app.util.*;
import com.app.vo.supermarket.MktLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Controller
@RestController
public class MktLoginController {

    @Autowired
    MktPersonService mktPersonService;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisService redisService;
    @GetMapping("/mktDoLogin")
    public String doLogin(String mobileCode) throws Exception {

        //TODO 可以增加自己的逻辑，关联业务相关数据
        Map<String, Object> body = getPhone(mobileCode);
        Map<String, String> phoneInfo = mapStringToMap(String.valueOf(body.get("phone_info")));
        String mobile = phoneInfo.get("phoneNumber");
        JSONObject json = new JSONObject();
        MktPersonModel customer =  mktPersonService.getModelByMobile(mobile);
        if(customer==null)
        {
            customer = new MktPersonModel();
            customer.setTellPhone(mobile);
            customer.setCrtTime(CommonHelp.getNowTimestamp());
            customer.setFaceUrl("https://www.mashangjiuye.cn/file/img/mface.webp");
            customer.setName("游客");
            mktPersonService.insert(customer);
        }
        String token= TokenUtils.sign(mobile);
        json.put("data",customer);
        json.put("access-token",token);
        json.put("code","1");
        json.put("msg","成功");
        return json.toString();
    }


    @GetMapping("/mktPcDoLogin")
    public Result<Object> mktPcDoLogin(String mobile){

        MktPersonModel customer =  mktPersonService.getModelByMobile(mobile);
        if(customer==null)
        {
            customer = new MktPersonModel();
            customer.setTellPhone(mobile);
            customer.setCrtTime(CommonHelp.getNowTimestamp());
            customer.setFaceUrl("https://www.mashangjiuye.cn/file/img/mface.webp");
            customer.setName("游客");
            mktPersonService.insert(customer);
        }
        MktLoginVo vo = new MktLoginVo();
        vo.setCustomer(customer);
        String token= TokenUtils.sign(mobile);
        vo.setToken(token);
        return Result.success(vo);
    }


    private static Map<String, String> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs) {
            String key = string.split("=")[0].trim();
            String value = string.split("=")[1];
            map.put(key, value);
        }
        return map;
    }
    public Map<String, Object> getPhone(String code) throws Exception {
        String token = WxQrCode.redisToken();
        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        System.out.println(httpEntity);
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
        return (Map<String, Object>) response.getBody();
    }
}